package git.soulbgm.service.impl;

import com.alibaba.fastjson.JSONObject;
import git.soulbgm.common.base.BaseServiceImpl;
import git.soulbgm.mapper.OrderMapper;
import git.soulbgm.pojo.OrderDto;
import git.soulbgm.pojo.Orders;
import git.soulbgm.service.OrderService;
import io.seata.integration.http.DefaultHttpExecutor;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

/**
 * 订单表
 *
 * @author SoulBGM
 * @version V1.0
 * @date 2020-11-06 17:27:16
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Orders> implements OrderService {

    @GlobalTransactional
    public Long createOrder(OrderDto dto) throws Exception {
        // 扣减库存
        reduceInventory(dto.getGoodsId(), dto.getAmount());
        // 扣减余额
        reduceBalance(dto.getAccountId(), dto.getPrice());
        // 保存订单
        Orders orders = new Orders();
        orders.setAccountId(dto.getAccountId());
        orders.setGoodsId(dto.getGoodsId());
        orders.setPayAmount(dto.getPrice());
        orders.setCreateTime(new Date());
        orders.setStatus(0);
        boolean result = save(orders);
        // 返回订单编号
        if (result) {
            return orders.getId();
        }
        return 0L;
    }

    private void reduceBalance(Long accountId, Double price) {
        try {
            // 参数拼接
            JSONObject params = new JSONObject().fluentPut("accountId", String.valueOf(accountId))
                    .fluentPut("price", String.valueOf(price));
            // 执行调用
            HttpResponse response = DefaultHttpExecutor.getInstance().executePost("http://127.0.0.1:9891", "/account/reduceBalance", params, HttpResponse.class);
            // 解析结果
            Boolean result = Boolean.valueOf(EntityUtils.toString(response.getEntity()));
            if (!result) {
                throw new RuntimeException("扣除库存失败");
            }
        } catch (IOException e) {
            throw new RuntimeException("扣除库存失败");
        }
    }

    private void reduceInventory(Long goodsId, Integer amount) {
        try {
            // 参数拼接
            JSONObject params = new JSONObject().fluentPut("goodsId", String.valueOf(goodsId))
                    .fluentPut("amount", String.valueOf(amount));
            // 执行调用
            HttpResponse response = DefaultHttpExecutor.getInstance().executePost("http://127.0.0.1:9892", "/goods/reduceInventory", params, HttpResponse.class);
            // 解析结果
            Boolean result = Boolean.valueOf(EntityUtils.toString(response.getEntity()));
            if (!result) {
                throw new RuntimeException("扣除余额失败");
            }
        } catch (IOException e) {
            throw new RuntimeException("扣除余额失败");
        }
    }

}